/******************************************************************************
* @file testFatfs.c
* @author Zohar
* @version 1.00
* @date 2019.09.21
* @brief
******************************************************************************/
#include "testFatfs.h"
#include "string.h"
#include "spiFlash.h"

void testFatfs(void)
{
    FATFS fs;             /* Filesystem object */
    FIL fil;              /* File object */
    FRESULT res;          /* API result code */
    UINT bw;              /* Bytes written */
    BYTE work[FF_MAX_SS]; /* Work area (larger is better for processing time) */
    BYTE mm[50];
    UINT i;
    uint32_t DataLength;

    /* 格式化文件系统 */
    res = f_mkfs("0:", 0, work, sizeof work); //"0:"是卷标，来自于 #define SPI_FLASH		0
    debug("f_mkfs res = %d\r\n", res);

    /* 挂载文件系统 */
    res = f_mount(&fs, "0:", 0);
    debug("f_mount res = %d\r\n", res);

    /* Create a file as new */
    res = f_open(&fil, "0:/test.txt", FA_CREATE_NEW | FA_WRITE | FA_READ);
    debug("f_open res = %d\r\n", res);

    /* Write a message */
    res = f_write(&fil, "Hello,World!", 12, &bw);
    debug("f_write res = %d\r\n", res);
    GetDataInSpiFlash(0, 1);
    GetDataInSpiFlash(63, 42);

    res = f_write(&fil, "good job!\r\n", sizeof("good job!\r\n"), &bw);
    debug("f_write res = %d\r\n", res);
    GetDataInSpiFlash(0, 1);
    GetDataInSpiFlash(63, 42);

    DataLength = f_size(&fil);
    debug("f_size DataLength = %d \r\n", DataLength);

    res = f_lseek(&fil, 0);
    debug("f_lseek res = %d \r\n", res);

    memset(mm, 0x0, 50);
    res = f_read(&fil, mm, DataLength, &i);
    debug("f_read res = %d \r\n", res);
    debug("%s\r\n", mm);

    /* Close the file */
    res = f_close(&fil);
    debug("f_close res = %d \r\n", res);
    GetDataInSpiFlash(0, 1);
    GetDataInSpiFlash(63, 42);

    /*卸载文件系统*/
    res = f_mount(0, "0:", 0);
    debug("f_mount res = %d \r\n", res);
}
